import os.path
import time

import requests
import json


class BaiduChatEngine(object):
    AppID = None
    APIKey = None
    SecretKey = None
    Host = "bcc.bj.baidubce.com"
    method = "PUT"
    query = "modiyAttribute"
    URI = "/v2/instance/i-YufwpQAe"

    def __init__(self):
        print("class BaiduChatEngine method init")
        # get xxx from config

        # current file path
        currentPath = os.path.abspath(__file__)
        configPath = os.path.dirname(currentPath) + os.path.sep + "config.json"
        print("[config.path]:" + configPath)

        if os.path.exists(configPath) == False:
            raise Exception()
        print('config file is existed. read message...')

        file = open(configPath, 'r')
        config = json.load(file)
        print(config)
        print(config['AppID'])

        self.AppID = config['AppID']
        self.APIKey = config['APIKey']
        self.SecretKey = config['SecretKey']

    def getAppID(self):
        return self.AppID

    def getAPIKey(self):
        return self.APIKey

    def getSecretKey(self):
        return 'xxxxxx'

    def getAccessToken(self):
        """
            使用 AK，SK 生成鉴权签名（Access Token）
            :return: access_token，或是None(如果错误)
            """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": self.APIKey,
            "client_secret": self.SecretKey
        }
        return str(requests.post(url, params=params).json().get("access_token"))

    def getHeader(self):
        header = {}

        header['Host'] = self.Host
        header['Content-Type'] = 'application/json;charset=utf-8'
        header['x-bce-date'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
        header['Authorization']

        return header

    def sendMessage(self, text):
        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_7b?access_token=" + self.getAccessToken()

        payload = json.dumps({
            "messages": [
                {
                    "role": "user",
                    "content": text
                }
            ]
        })

        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url=url, headers=headers, data=payload)
        print(response.text)

        return response.text
